#coding=utf-8
import sys

from uliweb.orm import get_model, set_dispatch_send, Begin, Commit, Rollback

error_log = None

set_dispatch_send(False)
#注意日期行的换行
def call(args, options, global_options):
    from uliweb.core.SimpleFrame import get_apps, get_app_dir, Dispatcher
    global error_log
    
    app = Dispatcher(apps_dir=global_options.apps_dir, start=False)
    Begin()
    error_log = open('upgrade_riskpoint_log.txt','w')
    try:
        try:
            if len(args) != 2:
                print "Usage: uliweb call upgrade_riskpoint riskpoint.txt"
                sys.exit(1)
                
            process(args[1], options, global_options)
            Commit()
        except Exception, e:
            Rollback()
            import traceback
            traceback.print_exc()
    finally:
        error_log.close()

def process(args, options, global_options):
    from uliweb.orm import get_model
    from parse_excel import open_book
    import csv
    import datetime
    from decimal import Decimal
    from uliweb.utils.date import to_date, to_datetime
    
    Risk = get_model('riskpoint')
    Solution = get_model('risksolution')
    Task = get_model('tasks_develop')
    
    Risk.modified_user.default = None
    Solution.modified_user.default = None
    
    f = fin = open(args, 'rb')
    n = 1
    r_n = 0
    s_n = 0
    try:
        first_line = f.readline()
        fields = first_line[1:].strip().split()
            
        for line in fin:
            try:
                n += 1
                line = eval(line.strip())
                record = dict(zip(fields, line))
                solution = Solution.get(Solution.c.solution_id==record['check_id'])
                if solution:
                    solution.update(solution_mode=record['solution_mode'],
                        nondev_riskpoint_status=record['nondev_riskpoint_status'],
                        task_id=record['task_id'])
                    solution.save()
                    s_n += 1
                    task = Task.get(record['task_id'])
                    if task:
                        solution.riskpoint.requirement = task._requirement_
                        solution.riskpoint.save()
                        r_n += 1
                else:
                    print "Can't found solution record %s Line: %d" % (record['check_id'], n)
                    error_log.write("Can't found solution record %s Line: %d\n" % (record['check_id'], n))
            except:
                error_log.write('Error: Line %d\n' % n)
                import traceback
                traceback.print_exc()
    finally:
        f.close()
    
    print 'Total %d records, %d risk point records updated, %d risk solution records updated' % (n, r_n, s_n)
    
